#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <event2/event.h>

void read_fifo (evutil_socket_t, short, void*);

int main()
{
    unlink("myfifo");
    //创建管道
    mkfifo("myfifo", 0664);

    //打开管道
    int fd = open("myfifo", O_RDONLY | O_NONBLOCK);
    if (fd == -1)
    {
        perror("open fifo");
        exit(1);
    }

    //创建事件处理框架
    struct event_base * base = NULL;
    base = event_base_new();

    //创建事件
    struct event *ev = NULL;
    ev = event_new(base, fd, EV_READ | EV_PERSIST, read_fifo, NULL);//

    //将事件添加到事件处理框架中
    event_add(ev, NULL);

    //开始事件循环
    event_base_dispatch(base);

    //释放资源
    event_free(ev);
    event_base_free(base);
    close(fd);

    return 0;
}

void read_fifo (evutil_socket_t fd, short what, void* arg)
{
    char buf[1024] = {0};
    int len = read(fd, buf, sizeof (buf));
    printf("have data = %s, len = %d, buf : %s\n",what & EV_READ ? "YES" : "NO", len, buf);
}
